package pay

import (
    "strconv"
	"encoding/json"
	"dhfshop/utils/math"
	"dhfshop/models/isv"
	"dhfshop/models/shopping"
	"dhfshop/controllers/base"
	"thirdpaysdk/api/chinaums"
	"github.com/astaxie/beego/validation"
	"github.com/astaxie/beego"
)

// 支付管理
type QueryController struct {
	base.BaseController
}

func (this *QueryController) QueryPayment() {
	var (
		//curAppId   string = ""
		//curOpenId  string = ""
		err        error
		acPay *isv.AcPayParams = nil
	)
	v := struct {
		OrderId  string   `form:"order_id" valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
    curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//beego.Debug("PayAddCommon payment:", v.Payment)
	if curRoleId != 2 {
	   this.ServeError("cur login role is invalid")
	   return
	}
	orderId, _ := strconv.ParseInt(v.OrderId, 10, 0)
	orders, err := shopping.GetOrderById(orderId)
	if err != nil {
		this.ServeError(err.Error())
		return      
	}
	acPay, err = isv.GetParamsByAppIdOrSubAppId(orders.AppId)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if acPay.PayWayId == 1||acPay.PayWayId == 2 {
	    
		
	} else if acPay.PayWayId == 16 {
		mid := acPay.MchId
		tid := acPay.SubMchId
		msgSrc := acPay.PemCert
		secreCode := acPay.Appkey
		rst, err := chinaums.OrderQuery(mid,tid,msgSrc,secreCode,v.OrderId)
		if err != nil {
		   beego.Debug("error:", err.Error())
		   this.ServeError(err.Error())
		   return
		}
		var srcMessage string
		totalFee := math.DivTotalFee(float32(rst.TotalAmount), 100)
		if tmpBody, err := json.Marshal(rst); err == nil {
		    srcMessage = string(tmpBody)
	    }
		_, err = shopping.AddPaymentByPayMsg(orders.PartnerId,orders.StoreId,orders.MemberId,orderId,1,
                        "1",rst.SeqId,"","","","",srcMessage,totalFee,0,0,0)			
		if err != nil {
		    this.ServeError(err.Error())
			return
		}
	} else {
	   this.ServeError("pay_way_id is invalid")
	   return
	}
	this.Data["json"] = "success"
	this.ServeJSON()
}
